from flask import request, current_app
from wtforms import Form

from app.error import ParameterError

log = current_app.logger


class BaseForm(Form):

    def __init__(self, location=None):
        # 若解析出错则抛出Werkzeug.BadRequest异常, 若silent设为True则返回None
        data = request.get_json(silent=True)
        query_string = request.args.to_dict()
        # Werkzeug的ImmutableMultiDict对象, 存储解析后的表单数据
        form_data = request.form
        super(BaseForm, self).__init__(
            formdata=form_data,
            data=data,
            **query_string
        )

    def api_validate(self):
        valid = super(BaseForm, self).validate()
        if not valid:
            # 错误绑定
            raise ParameterError(code=500, message=str(self.errors))

        return self
